  <template>
    <div class="device-management">
      <div class="page-header">
        <h2 class="page-title">设备管理</h2>
        <el-button type="primary" @click="showAddDialog" :disabled="loading" icon="el-icon-plus">
          新增设备
        </el-button>
      </div>

      <!-- 搜索和筛选区域 -->
      <el-card class="search-card">
        <el-form :inline="true" :model="searchForm" class="search-form" @submit.prevent>
          <el-form-item label="设备ID">
            <el-input
                v-model="searchForm.deviceId"
                placeholder="请输入设备ID"
                clearable
                @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="可用" value="available" />
              <el-option label="使用中" value="in_use" />
              <el-option label="维护中" value="maintenance" />
            </el-select>
          </el-form-item>
          <el-form-item label="自助点">
            <el-select v-model="searchForm.pointId" placeholder="请选择自助点" clearable>
              <el-option
                  v-for="point in selfServicePoints"
                  :key="point.pointId"
                  :label="point.name"
                  :value="point.pointId"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading" icon="el-icon-search">
              搜索
            </el-button>
            <el-button @click="resetSearch" icon="el-icon-refresh">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 设备列表 -->
      <el-table
          ref="table"
          :data="paginatedData"
          style="width: 100%"
          border
          v-loading="loading"
          class="custom-table"
          :default-sort="{ prop: 'deviceId', order: 'descending' }"
      >
        <el-table-column prop="deviceId" label="设备ID" width="100" sortable align="center" />
        <el-table-column label="自助点名称" min-width="150" sortable>
          <template #default="scope">
            {{ getSelfServicePointName(scope.row.pointId) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120" sortable align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)" effect="dark" size="small">
              {{ statusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastCleanedDate" label="上次清洁日期" width="150" sortable align="center">
          <template #default="scope">
            {{ formatDate(scope.row.lastCleanedDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" min-width="180" sortable align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right" align="center">
          <template #default="scope">
            <el-button
                type="primary"
                size="small"
                @click="showEditDialog(scope.row)"
                icon="el-icon-edit"
                style="margin-right: 10px"
            >
              编辑
            </el-button>
            <el-button
                type="danger"
                size="small"
                @click="deleteDevice(scope.row.deviceId)"
                icon="el-icon-delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="filteredData.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
        />
      </div>

      <!-- 新增/编辑对话框 -->
      <el-dialog
          :title="dialogTitle"
          v-model="dialogVisible"
          width="500px"
          custom-class="custom-dialog"
          :close-on-click-modal="false"
      >
        <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="dialog-form">
          <el-form-item label="自助点" prop="pointId">
            <el-select v-model="form.pointId" placeholder="请选择自助点" style="width: 100%">
              <el-option
                  v-for="point in filteredSelfServicePoints"
                  :key="point.pointId"
                  :label="point.name"
                  :value="point.pointId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
              <el-option label="可用" value="available" />
              <el-option label="使用中" value="in_use" />
              <el-option label="维护中" value="maintenance" />
            </el-select>
          </el-form-item>
          <el-form-item label="上次清洁" prop="lastCleanedDate">
            <el-date-picker
                v-model="form.lastCleanedDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false" :disabled="submitting">取消</el-button>
          <el-button
              type="primary"
              @click="submitForm"
              :loading="submitting"
              icon="el-icon-check"
          >
            确定
          </el-button>
        </template>
      </el-dialog>
    </div>
  </template>

  <script>
  import axios from 'axios';
  import _ from 'lodash';

  export default {
    name: 'DeviceManagement',
    data() {
      return {
        devices: [],
        selfServicePoints: [],
        dialogVisible: false,
        dialogTitle: '',
        loading: false,
        submitting: false,
        searchForm: {
          deviceId: '',
          status: '',
          pointId: '',
        },
        currentPage: 1,
        pageSize: 10,
        form: {
          deviceId: null,
          pointId: null,
          status: 'available',
          lastCleanedDate: null,
        },
        rules: {
          pointId: [{ required: true, message: '请选择自助点', trigger: 'change' }],
          status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        },
      };
    },
    computed: {
      adminInfo() {
        return this.$store.state.adminInfo || { username: 'admin', role: 'common' };
      },
      isSuperAdmin() {
        return this.adminInfo.role === 'super';
      },
      isCollapsed() {
        return this.$parent.isCollapsed;
      },
      filteredSelfServicePoints() {
        return this.selfServicePoints;
      },
      filteredData() {
        return this.devices.filter((device) => {
          const idMatch = this.searchForm.deviceId
              ? device.deviceId.toString().includes(this.searchForm.deviceId)
              : true;
          const statusMatch = this.searchForm.status
              ? device.status === this.searchForm.status
              : true;
          const pointMatch = this.searchForm.pointId
              ? device.pointId === this.searchForm.pointId
              : true;
          return idMatch && statusMatch && pointMatch;
        });
      },
      paginatedData() {
        const start = (this.currentPage - 1) * this.pageSize;
        const end = start + this.pageSize;
        return this.filteredData.slice(start, end);
      },
    },
    watch: {
      isCollapsed(newVal, oldVal) {
        if (newVal !== oldVal) {
          this.handleResizeDebounced();
        }
      },
    },
    mounted() {
      this.fetchDevices();
      this.fetchSelfServicePoints();
      this.$nextTick(() => {
        if (this.$refs.table) {
          this.handleResizeDebounced();
        }
      });
    },
    methods: {
      handleResizeDebounced: _.debounce(function () {
        this.$nextTick(() => {
          if (this.$refs.table && this.$refs.table.doLayout) {
            this.$refs.table.doLayout();
          }
        });
      }, 500),

      fetchDevices: _.debounce(async function () {
        try {
          this.loading = true;
          const token = sessionStorage.getItem('token');
          if (!token) {
            this.$message.error('未登录，请先登录');
            this.$router.push('/login');
            return;
          }

          const response = await axios.get('/api/devices', {
            headers: {
              Authorization: `Bearer ${token}`,
              Role: this.adminInfo.role || '',
              Username: encodeURIComponent(this.adminInfo.username || ''),
            },
          });

          this.devices = response.data.map(device => ({
            ...device,
            lastCleanedDate: device.lastCleanedDate ? device.lastCleanedDate.split('T')[0] : null,
            createdAt: device.createdAt || null,
          })) || [];
          if (this.devices.length === 0) {
            this.$message.info('暂无设备数据');
          }
        } catch (error) {
          const errorMsg = error.response?.data?.message || '获取设备列表失败';
          this.$message.error(errorMsg);
        } finally {
          this.loading = false;
        }
      }, 300),

      fetchSelfServicePoints: _.debounce(async function () {
        try {
          const token = sessionStorage.getItem('token');
          if (!token) {
            this.$message.error('未登录，请先登录');
            this.$router.push('/login');
            return;
          }

          const response = await axios.get('/api/self-service-points', {
            headers: {
              Authorization: `Bearer ${token}`,
              Role: this.adminInfo.role || '',
              Username: encodeURIComponent(this.adminInfo.username || ''),
            },
          });

          this.selfServicePoints = response.data || [];
          if (this.selfServicePoints.length === 0) {
            this.$message.info('暂无自助点数据');
          }
        } catch (error) {
          const errorMsg = error.response?.data?.message || '获取自助点列表失败';
          this.$message.error(errorMsg);
        }
      }, 300),

      getSelfServicePointName(pointId) {
        const point = this.selfServicePoints.find((p) => p.pointId === pointId);
        return point ? point.name : '未知';
      },

      statusText(status) {
        const map = {
          available: '可用',
          in_use: '使用中',
          maintenance: '维护中',
        };
        return map[status] || status;
      },

      getStatusTagType(status) {
        const map = {
          available: 'success',
          in_use: 'warning',
          maintenance: 'danger',
        };
        return map[status] || '';
      },

      formatDate(date) {
        if (!date) return 'N/A';
        return new Date(date)
            .toLocaleDateString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
            })
            .replace(/\//g, '-');
      },

      formatDateTime(dateTime) {
        if (!dateTime) return 'N/A';
        return new Date(dateTime)
            .toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit',
              second: '2-digit',
              hour12: false,
            })
            .replace(/\//g, '-');
      },

      handleSearch() {
        this.currentPage = 1;
      },

      resetSearch() {
        this.searchForm = { deviceId: '', status: '', pointId: '' };
        this.currentPage = 1;
      },

      handleSizeChange(val) {
        this.pageSize = val;
        this.currentPage = 1;
        this.handleResizeDebounced();
      },

      handleCurrentChange(val) {
        this.currentPage = val;
        this.handleResizeDebounced();
      },

      showAddDialog() {
        if (this.selfServicePoints.length === 0) {
          this.$message.warning('请先添加自助点');
          return;
        }
        this.dialogTitle = '新增设备';
        this.form = {
          deviceId: null,
          pointId: this.selfServicePoints[0]?.pointId || null,
          status: 'available',
          lastCleanedDate: null,
        };
        this.openDialog();
      },

      showEditDialog(row) {
        this.dialogTitle = '编辑设备';
        this.form = {
          ...row,
          lastCleanedDate: row.lastCleanedDate || null,
        };
        this.openDialog();
      },

      openDialog() {
        this.dialogVisible = true;
        this.$nextTick(() => {
          this.$refs.formRef?.clearValidate();
        });
      },

      submitForm() {
        this.$refs.formRef.validate(async (valid) => {
          if (!valid) return;

          this.submitting = true;
          try {
            const token = sessionStorage.getItem('token');
            if (!token) {
              this.$message.error('未登录，请先登录');
              this.$router.push('/login');
              return;
            }

            const payload = {
              pointId: this.form.pointId,
              status: this.form.status,
              lastCleanedDate: this.form.lastCleanedDate || null,
            };

            const config = {
              headers: {
                Authorization: `Bearer ${token}`,
                Role: this.adminInfo.role || '',
                Username: encodeURIComponent(this.adminInfo.username || ''),
              },
            };

            if (this.form.deviceId) {
              await axios.put(`/api/devices/${this.form.deviceId}`, payload, config);
              this.$message.success('设备更新成功');
            } else {
              await axios.post('/api/devices', payload, config);
              this.$message.success('设备添加成功');
            }

            this.dialogVisible = false;
            this.fetchDevices();
          } catch (error) {
            const errorMsg = error.response?.data?.message || '操作失败';
            this.$message.error(errorMsg);
          } finally {
            this.submitting = false;
          }
        });
      },

      deleteDevice(deviceId) {
        this.$confirm('确定删除此设备吗？此操作不可撤销', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
            .then(async () => {
              try {
                const token = sessionStorage.getItem('token');
                if (!token) {
                  this.$message.error('未登录，请先登录');
                  this.$router.push('/login');
                  return;
                }

                await axios.delete(`/api/devices/${deviceId}`, {
                  headers: {
                    Authorization: `Bearer ${token}`,
                    Role: this.adminInfo.role || '',
                    Username: encodeURIComponent(this.adminInfo.username || ''),
                  },
                });

                this.$message.success('设备删除成功');
                this.fetchDevices();
              } catch (error) {
                const errorMsg = error.response?.data?.message || '删除失败';
                this.$message.error(errorMsg);
              }
            })
            .catch(() => {
              this.$message.info('已取消删除');
            });
      },
    },
  };
  </script>

  <style scoped>
  .device-management {
    padding: 24px;
    background: #f5f7fa;
    min-height: calc(100vh - 96px);
    width: 100%;
  }

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
  }

  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0;
  }

  .search-card {
    margin-bottom: 24px;
    border-radius: 8px;
    background: #fff;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  }

  .search-form {
    padding: 10px 0;
  }

  .custom-table {
    border-radius: 8px;
    overflow: hidden;
    background: #fff;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    height: calc(100vh - 300px); /* 替换 max-height，调整为适合布局 */
    overflow: auto;
  }

  .custom-table :deep(.el-table__header-wrapper th) {
    background-color: #fafafa;
    color: #606266;
    font-weight: 600;
  }

  .pagination-container {
    padding: 20px 0;
    display: flex;
    justify-content: flex-end;
  }

  .custom-dialog {
    border-radius: 8px;
  }

  .dialog-form {
    padding: 0 20px;
  }

  .el-button {
    border-radius: 6px;
    transition: all 0.3s;
  }

  .el-button:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .el-button[type="primary"] {
    background: #409eff;
    border-color: #409eff;
  }

  .el-button[type="danger"] {
    background: #f56c6c;
    border-color: #f56c6c;
  }

  .el-form-item {
    margin-bottom: 20px;
  }

  :deep(.el-dialog__header) {
    border-bottom: 1px solid #f0f0f0;
    padding-bottom: 15px;
  }

  :deep(.el-dialog__footer) {
    border-top: 1px solid #f0f0f0;
    padding-top: 15px;
  }
  </style>